package com.gcloud.mesh.dcs.task;


import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import com.gcloud.mesh.dcs.dao.SchedulerJobDao;
import com.gcloud.mesh.dcs.dao.SchedulerStepDao;
import com.gcloud.mesh.dcs.entity.SchedulerStepEntity;
import com.gcloud.mesh.dcs.enums.SchedulerJobStatus;
import com.gcloud.mesh.dcs.enums.SchedulerStepStatus;

import lombok.extern.slf4j.Slf4j;


/**
 * 检测虚拟机迁移任务状态 status = 2 scheduler_type in ('ali','huawei')
 */

@Slf4j
//@Component
public class CheckVMStatusOuttimeTask {

    @Autowired
    private SchedulerStepDao schedulerStepDao;

    @Autowired
    private SchedulerJobDao schedulerJobDao;

    @Autowired
    private RedisUtil redisUtil;

    @Scheduled(fixedDelay = 1000 * 60)
    public void doExec() {
        String uuid = UUID.randomUUID().toString();
        try {
            log.info(uuid+"[CheckVMStatusTask] 检测虚拟机迁移超时任务状态定时器开始【超过12小时未完成】");
            String sql = "select * from dcs_scheduler_steps t " +
                    " where  t.status = 1 and scheduler_type in ('ali','huawei') and end_time is null " +
                    " and now() >= TIMESTAMPADD(MINUTE, 12*60, begin_time)" +
                    " order by begin_time" +
                    "";
            List<SchedulerStepEntity> stepEntityList = schedulerStepDao.findBySql(sql, SchedulerStepEntity.class);
            if(stepEntityList!=null && !stepEntityList.isEmpty()){
                log.info(uuid+"一共有"+stepEntityList.size()+"个超时任务");
                for (SchedulerStepEntity schedulerStepEntity : stepEntityList) {
                    schedulerStepEntity.setEndTime(new Date());
                    schedulerStepEntity.setStatus(SchedulerStepStatus.FAIL.getValue());
                    schedulerStepDao.update(schedulerStepEntity);
                    schedulerJobDao.updateJobStatusById(schedulerStepEntity.getSchedulerJobId(), SchedulerJobStatus.FAIL);
//                    redisUtil.del(String.format("job:transfer:%s",jobEntity.getAppId()));

                }
            }else{
                log.info(uuid+"没有需要处理的超时任务");
            }

        }finally {
            log.info(uuid+"[CheckVMStatusTask] 检测虚拟机迁移超时任务状态定时器结束【超过12小时未完成】");
        }




    }
}
